package com.zchat.api.connection;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import com.zchat.api.ZChat;

/**
 * 
 * @author Oliverzhu
 * 向服务器发送请求，获得相应时间，判断时间差，选择网络
 */

public class PingServer {

	private static float RESP_TIME = -1; // 服务器响应返回时间
	private static long PING_TIME_OUT = 3*1000; // ping值超时时间
	
	/**
	 * PING服务器
	 */
	private static class PING_Thread extends Thread {
		public void run() {
			RESP_TIME = getSharkHandTime(ZChat.ZCHAT_DOMAIN);
		}
	};


	/**
	 * 返回当前可用的服务器地址
	 * 
	 * @return
	 * @throws Exception
	 * @author huang_bo
	 */
	public static Server getAvailableServer() throws Exception {
		// 进行ping值
		PING_Thread ping_Thread = new PING_Thread();
		
		ping_Thread.start();
		// 获得当前系统时间
		long startTime = System.currentTimeMillis();
		// 等待ping返回值
		while (true) {
			long currTime = System.currentTimeMillis();
			if (RESP_TIME != -1) {
				break;
			}
			// 等待超过三秒，未有值，则退出
			long offset = currTime - startTime;
			if (offset > PING_TIME_OUT) {
				break;
			}
			try {
				Thread.sleep(300);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 比较确定使用哪条线路
		if (RESP_TIME == -1) {
			// 当前网络不可用，默认返回电信服务器
			// 修改为返回无服务器
			return Server.other;
		} else
		{
			return Server.mServer;
		}

	}

	/**
	 * 得到ping一个网址的时间
	 * 
	 * @param urlAddress
	 * @return
	 */
	private static float getSharkHandTime(String urlAddress) {
		if (urlAddress == null || urlAddress.trim().equals("")) {
			return -1;
		}
		// 判断urlAddress是否有端口号，有则去掉
		int index1 = urlAddress.indexOf("//");
		if (index1 != -1) {
			urlAddress = urlAddress.substring(index1 + 2);
		}
		int index2 = urlAddress.indexOf(":");
		if (index2 != -1) {
			urlAddress = urlAddress.substring(0, index2);
		}
//		Logger.debug("Start to ping ip : " + urlAddress);
		try {
			Process p = Runtime.getRuntime().exec("ping -c 1 " + urlAddress);

			int status = p.waitFor();
			if (status == 0) {
				String line = null;
				BufferedReader buf = new BufferedReader(new InputStreamReader(
						p.getInputStream()));
				int i = 1;
				while ((line = buf.readLine()) != null) {
					if (i == 2) {
						String temp = line.substring(line.lastIndexOf("=") + 1,
								line.lastIndexOf("ms"));
						float time = Float.parseFloat(temp.trim());
//						System.out.println("time:" + time);
						return time;
					}

					i++;
				}
			} else {
//				Logger.debug("Ping server completed and no server.");
				return -1;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}

		return -1;
	}

	public static Server changeNet() {
		// if()
		return null;
	}

}